import os
import sys
import sqlite3
import django

sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')
django.setup()

from apps.flowers.models import Flower, FlowerImage

def sync_flower_images_from_sqlite():
    """从SQLite同步flower_image表数据到MySQL"""
    
    sqlite_db_path = '../backend/db.sqlite3'
    if not os.path.exists(sqlite_db_path):
        print("SQLite数据库文件不存在")
        return
    
    # 连接SQLite数据库
    conn = sqlite3.connect(sqlite_db_path)
    cursor = conn.cursor()
    
    try:
        # 检查SQLite中的flower_image表
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='flower_image';")
        if not cursor.fetchone():
            print("SQLite中没有找到flower_image表")
            return
        
        # 清空MySQL中的flower_image表
        print("清空MySQL中的flower_image表...")
        FlowerImage.objects.all().delete()
        
        # 从SQLite读取flower_image数据
        cursor.execute("SELECT * FROM flower_image")
        columns = [description[0] for description in cursor.description]
        print(f"SQLite flower_image表字段: {columns}")
        
        flower_images = cursor.fetchall()
        print(f"找到 {len(flower_images)} 条图片记录")
        
        success_count = 0
        error_count = 0
        
        for img_data in flower_images:
            try:
                # 创建字典映射
                img_dict = dict(zip(columns, img_data))
                print(f"处理图片记录: {img_dict}")
                
                # 查找对应的花卉
                flower_id = img_dict.get('flower_id')
                if not flower_id:
                    print(f"跳过：没有flower_id")
                    continue
                
                # 先通过名称查找花卉（因为ID可能不匹配）
                cursor.execute("SELECT name FROM flower WHERE id = ?", (flower_id,))
                flower_name_result = cursor.fetchone()
                if not flower_name_result:
                    print(f"跳过：SQLite中找不到ID为{flower_id}的花卉")
                    continue
                
                flower_name = flower_name_result[0]
                mysql_flower = Flower.objects.filter(name=flower_name).first()
                if not mysql_flower:
                    print(f"跳过：MySQL中找不到名为'{flower_name}'的花卉")
                    continue
                
                # 创建FlowerImage记录
                flower_image = FlowerImage.objects.create(
                    flower=mysql_flower,
                    image_url=img_dict.get('image_url', ''),
                    is_main=bool(img_dict.get('is_primary', False)),  # SQLite中可能是is_primary
                    sort_order=img_dict.get('sort_order', 0)
                )
                
                print(f"✓ 成功同步: {flower_name} -> {img_dict.get('image_url')}")
                success_count += 1
                
            except Exception as e:
                print(f"✗ 同步失败: {e}")
                error_count += 1
        
        print(f"\n同步完成！成功: {success_count}, 失败: {error_count}")
        
        # 验证同步结果
        print("\n验证同步结果:")
        mysql_images = FlowerImage.objects.all()
        for img in mysql_images:
            print(f"{img.flower.name}: {img.image_url} (主图: {img.is_main})")
        
    except Exception as e:
        print(f"同步过程出错: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    sync_flower_images_from_sqlite()